import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import user from './user'
import _ from "lodash"

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function sortAsyncRoutes(menus, routes) {
  // 菜单排序
  let newArr = [];
  menus.forEach(item => {
    routes.forEach(route => {
      const tmp = {
        ...route
      }
      if (item.menuName == route.meta.title) {
        if (tmp.children) {
          tmp.children = sortAsyncRoutes(item.children, route.children)
        }
        newArr.push(tmp);
      }
    })
  })
  return newArr
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles, menuObj) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (menuObj[tmp.path]) {
      tmp.meta.title = menuObj[tmp.path]
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles, menuObj)
      }
      res.push(tmp)
    }
  })

  return res
}
export function forEachRoute(routes, menuObj) {
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (tmp.children && _.size(tmp.children) > 0) {
      forEachRoute(tmp.children, menuObj)
    }
    if (tmp.url && tmp.url != '#' && tmp.menuType != 'F') menuObj[tmp.url] = tmp.menuName;
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({
    commit
  }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        let menuObj = {};
        forEachRoute(user.state.menus, menuObj)
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, menuObj);
      }
      accessedRoutes = sortAsyncRoutes(user.state.menus, accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
